package com.sghy.xcxservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sghy.xcxservice.common.CustomException;
import com.sghy.xcxservice.common.Error;
import com.sghy.xcxservice.common.Fn;
import com.sghy.xcxservice.common.JWTUtil;
import com.sghy.xcxservice.entity.BgbLogin;
import com.sghy.xcxservice.entity.BgbLoginUser;
import com.sghy.xcxservice.entity.BgbOrgUser;
import com.sghy.xcxservice.service.BgbLoginService;
import com.sghy.xcxservice.mapper.BgbLoginMapper;
import com.sghy.xcxservice.service.BgbLoginUserService;
import com.sghy.xcxservice.service.BgbOrgUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author pc
* @description 针对表【bgb_login(登录信息表)】的数据库操作Service实现
* @createDate 2025-05-29 18:10:16
*/
@Service
public class BgbLoginServiceImpl extends ServiceImpl<BgbLoginMapper, BgbLogin>
    implements BgbLoginService{
    
    @Autowired
    private BgbLoginUserService bgbLoginUserService;
    
    @Autowired
    private BgbOrgUserService bgbOrgUserService;
    @Override
    public String login(String username, String password) {
        QueryWrapper<BgbLogin> where = new QueryWrapper<>();
        where.eq("user_name", username);
        BgbLogin Login = getOne(where);
        if (Login == null) {
            throw new CustomException(Error.NO_USER);
        }else {
            String[] encryptPassword = Fn.encryptPassword(password, Login.getEncrypt());
            if (Login.getPassword().equals(encryptPassword[0])) {
                List<BgbLoginUser> loginUserList = bgbLoginUserService.getLoginUserListByLoginIdOrderTime(Login.getId());
                for (BgbLoginUser loginUser : loginUserList) {
                    if (loginUser.getStatus() == 0) {
                        BgbOrgUser orgUser = bgbOrgUserService.getByUid(loginUser.getUId());
                        if (orgUser != null) {
                            JWTUtil jwtUtil = new JWTUtil();
                            return jwtUtil.generateToken(loginUser.getUId());
                        }
                    }
                }
                throw new CustomException(Error.NO_USER);
            }else {
                throw new CustomException(Error.ERROR,"密码错误！");
            }
        }
    }
}




